module.exports = ( app ) => {

	// Add headers
	app.use ( (req, res, next) =>  {

	    res.setHeader ( 'Access-Control-Allow-Origin', '*' );

	    res.setHeader ( 'Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE' );

	    res.setHeader ( 'Access-Control-Allow-Headers', 'X-Requested-With,content-type' );

  		res.setHeader ( 'Access-Control-Allow-Credentials', true );

	    next (  );
	} );

	app.get ( app.config.api + '/user/:id', ( req, res, next ) => {

		( new app.config.models.User (  ) ).search ( { "id": req.params.id }, ( resp ) => {

      res.send ( resp )
    } )
	} )

  app.delete ( app.config.api + '/user/:id', ( req, res, next ) => {

  	( new app.config.models.User (  ) ).removeUser ( {
			"id": req.params.id
		}, ( resp ) => {

      res.send ( resp )
    } )
  } )

	app.get ( app.config.api + '/user', ( req, res, next ) => {

		( new app.config.models.User (  ) ).show ( ( resp ) => {

      res.send ( resp )
    } )
	} )

	app.put ( app.config.api + '/user/:id', ( req, res, next ) => {

		( new app.config.models.User (  ) ).update( {
        name: req.body.name,
        login: req.body.login,
        pass: req.body.pass,
        repass: req.body.repass,
        email: req.body.email,
        city: req.body.city,
				points: req.body.points
      }, {
        email: req.body.emailBefore
      }, ( resp ) => {

        res.send ( resp )
      } )

	} )

	app.post ( app.config.api + '/user', ( req, res, next ) => {

		let dataRequest = {
      name: req.body.name,
      login: req.body.login,
      pass: req.body.pass,
      repass: req.body.repass,
      email: req.body.email,
      city: req.body.city,
			points: req.body.points
    }

		let user = ( new app.config.models.User (  ) )

		let valueCheckFields = user.check({valid: {
		      value: true,
		      data: dataRequest
		    }
		})

		if ( valueCheckFields.status ) {

   		user.add( dataRequest, ( resp ) => {

        res.send ( resp )
      } )
		} else {

		  res.send ( {
				status: "error"
			} )
		}

	} )

	return app
}
